package com.enzoism.mvc.controller;

import com.alibaba.fastjson.JSONObject;
import com.enzoism.mvc.config.AutowireFactory;
import com.enzoism.mvc.config.UserFactory;
import com.enzoism.mvc.model.TestUser;
import com.enzoism.mvc.util.SpringContextUtil;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class MyController {
    /**
     * 直接返回一个数据到页面上
     */
    @GetMapping("hello")
    @ResponseBody
    public String hello() {
        return "first";
    }

    /**
     * 重定向到一个页面上
     */
    @GetMapping("hello2")
    public String hello2() {
        return "first";
    }

    @GetMapping("bean1")
    @ResponseBody
    public String bean1() {
        ApplicationContext applicationContext = new FileSystemXmlApplicationContext("classpath:springmvc.xml");
        TestUser testUser = applicationContext.getBean("testUser", TestUser.class);
        return JSONObject.toJSONString(testUser);
    }

    @GetMapping("bean2")
    @ResponseBody
    public String bean2() {
        TestUser testUser = SpringContextUtil.getBean("testUser2", TestUser.class);
        return JSONObject.toJSONString(testUser);
    }

    @GetMapping("bean3")
    @ResponseBody
    public String bean3() {
        // 1.先获取应用上下文
        ApplicationContext applicationContext = SpringContextUtil.getApplicationContext();
        // 2.添加AutowireBeanFactory来获取bean工厂
        AutowireCapableBeanFactory autowireCapableBeanFactory = applicationContext.getAutowireCapableBeanFactory();
        // 3.使用bean工厂创建对象
        UserFactory userFactory = autowireCapableBeanFactory.createBean(AutowireFactory.class);
        TestUser testUser = userFactory.createUser();
        return JSONObject.toJSONString(testUser);
    }

    @GetMapping(value = "xml", produces = MediaType.APPLICATION_XML_VALUE)
    @ResponseBody()
    public TestUser xml() {
        return new TestUser("Xml");
    }

}
